<?php
class cache {
	private $cache_dir;

	public function cache($cache_dir = "./cache") {
		// /home/kestutis/public_html/projektai/mightmedia
		$this->cache_dir = $cache_dir;
		unset($cache_dir);
		return true;
	}

	private function createDir($dir_name) {
		if (is_dir($dir_name))
			return TRUE;
		else
			return mkdir($dir_name, 0777);//Turetu kreiptis i FTP del teisiu...
			//tik nesuprantu kam reikia kurti direktorijas. /blokai/kashe_failas.php gali buti saugojamas pavadinimu md5("/blokai/kashe_failas.php");
	}

	public function getTypes() {
		$types = array();

		$d = dir($this->cache_dir);
		while (false !== ($entry = $d->read())) {
			if (strpos($entry, '.') !== 0)
			$types[] = $entry;
		}
		$d->close();

		return $types;
	}

	public function get($type, $file) {
		if (file_exists("$this->cache_dir/$type/$file.dat")) {
			$value = file_get_contents("$this->cache_dir/$type/$file.dat");

			$expires = trim(substr($value, 0, 16));
			$value = substr($value, 16);

			if (!$expires || $expires > time())
				return unserialize($value);
			else
				$this->remove($type, $file);
		}
		return false;
	}

	public function set($type, $file, $value, $expires = '0') {
		$filename = "$this->cache_dir/$type/$file.dat";

		//IF not exist - create
		$this->createDir("$this->cache_dir/$type");
		
        
		$expires = str_pad($expires, 16, ' ', STR_PAD_RIGHT);
		$value = $expires.serialize($value);

		$fp = fopen($filename, 'a+');
		if (flock($fp, LOCK_EX)) {
			ftruncate($fp, 0);
			fwrite($fp, $value, strlen($value));
			fclose($fp);
			// chmod($filename, 0666);
		} else
			fclose($fp);

		return $value;
	}

	public function remove($type, $file) {
		if (file_exists("$this->cache_dir/$type/$file.dat"))
			return unlink("$this->cache_dir/$type/$file.dat");
	}

	public function removeType($type) {
		//return exec("rm -rf $this->cache_dir/$type");
		return rmdir("$this->cache_dir/$type");
	}
	/*
	function check_cache($file, $cache_timeout=0) {

		if(file_exists($file)) {	// file exists

			$filetime	= filemtime($file);
			$fileage	= time() - $filetime;
		
		if($cache_timeout > $fileage) {
				return 'VALID';		// file is up-to-date
			} else {
				return 'EXPIRED';	// file is too old and expired
			}
	
		} else {

			return 'MISSING';		// file not present

		}
	}
	*/
}
?>
